package com.yuju.login.service.impl;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yuju.common.PageModel;
import com.yuju.common.Result;
import com.yuju.common.core.dao.IBaseDao;
import com.yuju.common.core.service.AbstractBaseService;
import com.yuju.enums.ReturnCodeEnum;
import com.yuju.enums.ReturnStatusEnum;
import com.yuju.enums.StatusEnum;
import com.yuju.enums.UserTypeEnum;
import com.yuju.exception.BusinessException;
import com.yuju.login.dao.IOpDao;
import com.yuju.login.dao.entity.Op;
import com.yuju.login.enums.OpReturnCodeEnum;
import com.yuju.login.model.OpHotelModel;
import com.yuju.login.model.OpModel;
import com.yuju.login.service.IOpHotelService;
import com.yuju.login.service.IOpService;
import com.yuju.util.Utils;
/**
 * 
 * 类名：OpServiceImpl  <br />
 *
 * 功能：
 *
 * @author : zhousc <br />
 * @Date : 2017年11月27日 上午10:34:24  <br />
 * @version : 1.1 <br />
 */
@Service
public class OpServiceImpl extends AbstractBaseService<OpModel, Op, String> implements IOpService{

	@Autowired
	private IOpDao opDao;
	@Autowired
	private IOpHotelService opHotelService;
	
	@Override
	public IBaseDao<OpModel, Op, String> getDao() {
		// TODO Auto-generated method stub
		return opDao;
	}

	/**
	 * 
	 * 功能：列表<br/>
	 *
	 * @author zhousc
	 * @Date 2017年12月5日 下午2:03:59 <br/>
	 */
	@Override
	public PageModel pageList(OpModel opModel, Integer currentPage, Integer rows) {
		opModel.setUserType((byte)1);
		PageModel pageModel = getDao().list(opModel, currentPage, rows);
		List<OpModel> opModels = (List<OpModel>)pageModel.getRows();
		if(opModels.size() != 0){
			//查询分店数据范围，拼接分店数据范围字段
			for(int i = 0; i < opModels.size(); i++){
				List<OpHotelModel> hotelListByOpId = opHotelService.hotelListByOpId(opModels.get(i).getId());
				if(null != hotelListByOpId && hotelListByOpId.size() != 0){
					for(int z = 0; z < hotelListByOpId.size(); z++){
						if(Utils.isNull(opModels.get(i).getHotelNames())){
							opModels.get(i).setHotelNames(hotelListByOpId.get(z).getHotelName());
						} else {
							opModels.get(i).setHotelNames(opModels.get(i).getHotelNames()+","+hotelListByOpId.get(z).getHotelName());
						}
					}
				}
			}
		}
		return pageModel;
	}
	
	/**
	 * 
	 * 功能: 新增账号<br/>
	 * 
	 * 重写：zhousc <br/>
	 * 
	 * @Date ：2017年12月4日 上午10:51:45<br/>
	 * 
	 * @param opModel
	 * @return <br/>
	 * @see com.yuju.common.core.service.AbstractBaseService#save(java.lang.Object)
	 */
	@Override
	public int save(OpModel opModel){
		opModel.setId(Utils.getUUID());
		opModel.setUserType(UserTypeEnum.PMS_USER.getValue());
		opModel.setGmtCreate(new Date());
		opModel.setGmtModified(new Date());
		opModel.setSalt(Utils.getUUID());
		
		//对密码加密
		String empId = opModel.getEmpId();
		String password = opModel.getPassword();
		String salt = opModel.getSalt();
		//组合新密码
		String newPwd = empId + password + salt;
		//进行SHA加密
		try {
			MessageDigest instance = MessageDigest.getInstance("SHA-256");
			byte[] digest = instance.digest(newPwd.getBytes("UTF-8"));
			//产生加密密码
			String encodeHexString = Hex.encodeHexString(digest);
			//装载数据
			opModel.setPassword(encodeHexString);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//账号添加
		this.getDao().saveSelective(opModel);
		//关联分店添加
		OpHotelModel opHotelModel = new OpHotelModel();
		opHotelModel.setGroupId(opModel.getGroupId());
		opHotelModel.setOpId(opModel.getId());
		opHotelModel.setHotelIds(opModel.getHotelIds());
		
		opHotelService.save(opHotelModel);
		
		return 1;
	}
	
	public int updateOp(OpModel opModel) {
		opModel.setIsAdmin(StatusEnum.FALSE.getValue());
		opModel.setGmtModified(new Date());
		return super.updateSelective(opModel);
	}
	
	/**
	 * 
	 * 功能: 账号更新<br/>
	 * 
	 * 重写：zhousc <br/>
	 * 
	 * @Date ：2017年12月4日 上午10:51:48<br/>
	 * 
	 * @param opModel
	 * @return <br/>
	 * @see com.yuju.common.core.service.AbstractBaseService#updateSelective(java.lang.Object)
	 */
	@Override
	public int updateSelective(OpModel opModel){
		opModel.setIsAdmin(StatusEnum.FALSE.getValue());
		opModel.setGmtModified(new Date());
		//判断密码是否改动
		OpModel model = convert(this.getDao().getObj(opModel.getId()));
		//如果和数据库不一致，对密码重新加密保存
		if(!model.getPassword().equals(opModel.getPassword())){
			opModel.setSalt(Utils.getUUID());
			//对密码加密
			String empId = opModel.getEmpId();
			String password = opModel.getPassword();
			String salt = opModel.getSalt();
			//组合新密码
			String newPwd = empId + password + salt;
			//进行SHA加密
			try {
				MessageDigest instance = MessageDigest.getInstance("SHA-256");
				byte[] digest = instance.digest(newPwd.getBytes("UTF-8"));
				//产生加密密码
				String encodeHexString = Hex.encodeHexString(digest);
				//装载数据
				opModel.setPassword(encodeHexString);
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		//账号信息更新
		this.getDao().updateSelective(opModel);
		//关联分店更新
		OpHotelModel opHotelModel = new OpHotelModel();
		opHotelModel.setGroupId(opModel.getGroupId());
		opHotelModel.setOpId(opModel.getId());
		opHotelModel.setHotelIds(opModel.getHotelIds());
		opHotelService.updateSelective(opHotelModel);
		
		return 1;
	}
	/**
	 * 
	 * 功能:账号删除，并删除ophotel表的数据 <br/>
	 * 
	 * 重写：zhousc <br/>
	 * 
	 * @Date ：2017年12月4日 下午5:02:37<br/>
	 * 
	 * @param id
	 * @return <br/>
	 * @see com.yuju.common.core.service.AbstractBaseService#del(java.lang.Object)
	 */
	@Override
	public int del(String id){
		this.getDao().del(id);
		opHotelService.del(id);
		return 1;
	}

	/**
	 * 
	 * 功能:密码登录时查询账号信息 <br/>
	 * 
	 * 重写：zhousc <br/>
	 * 
	 * @Date ：2017年12月5日 上午9:53:21<br/>
	 * 
	 * @param name
	 * @return <br/>
	 * @see com.yuju.login.service.IOpService#pwdLoginFindByName(java.lang.String)
	 */
	@Override
	public OpModel pwdLoginFindByName(String name) {
		// TODO Auto-generated method stub
		return convert(opDao.pwdLoginFindByName(name));
	}
	
	/**
	 * 
	 * 功能：根据ID获取账号信息<br/>
	 *
	 * @author zhousc
	 * @Date 2017年12月5日 下午2:18:30 <br/>
	 */
	@Override
	public OpModel findById(String id) {
		OpModel opModel = convert(this.getDao().getObj(id));
		opModel.setEmpId(opModel.getUserId());
		//根据ID查询分店数据范围
		List<OpHotelModel> hotelListByOpId = opHotelService.hotelListByOpId(id);
		String[] aArray = new String[hotelListByOpId.size()]; 
		for(int i = 0; i <hotelListByOpId.size(); i++){
			aArray[i] = hotelListByOpId.get(i).getHotelId();
		}
		opModel.setHotelIds(aArray);
		return opModel;
	}
	/**
	 * 
	 * 功能:个人中心，修改密码 <br/>
	 * 
	 * 重写：zhousc <br/>
	 * 
	 * @Date ：2017年12月6日 下午2:28:55<br/>
	 * 
	 * @param opModel
	 * @return <br/>
	 * @see com.yuju.login.service.IOpService#updatePassword(com.yuju.login.model.OpModel)
	 */
	@Override
	public Result updatePassword(OpModel model) {
		Result result = new Result();
		//首先判断 新密码不能为空
		if (Utils.isNull(model.getNewPassword())) {
			result.setStatus(ReturnStatusEnum.SUCCESS.getCode());
			result.setMsg(ReturnStatusEnum.SUCCESS.getDesc());
			result.setReturnCode(OpReturnCodeEnum.OP_NEWPASSWORD_NODATA.getCode());
			result.setReturnMsg(OpReturnCodeEnum.OP_NEWPASSWORD_NODATA.getDesc());
			return result; 
		}
		
		//判断原始密码是否正确
		OpModel opModel = convert(this.getDao().getObj(model.getId()));
		
		//对原始密码加密比较
		String pwd = opModel.getUserId() + model.getPassword() + opModel.getSalt();
		//进行SHA加密
		try {
			MessageDigest instance = MessageDigest.getInstance("SHA-256");
			byte[] digest = instance.digest(pwd.getBytes("UTF-8"));
			//产生加密密码
			String encodeHexString = Hex.encodeHexString(digest);
			//判断原始密码是否正确
			if (!encodeHexString.equals(opModel.getPassword())) {
				result.setStatus(ReturnStatusEnum.SUCCESS.getCode());
				result.setMsg(ReturnStatusEnum.SUCCESS.getDesc());
				result.setReturnCode(OpReturnCodeEnum.OP_NEWPASSWORD_FAILURE.getCode());
				result.setReturnMsg(OpReturnCodeEnum.OP_NEWPASSWORD_FAILURE.getDesc());
				return result; 
			}
			
			//如果原始密码正确，保存新密码
			//对原始密码加密比较
			String newPwd = opModel.getUserId() + model.getNewPassword() + opModel.getSalt();
			instance = MessageDigest.getInstance("SHA-256");
			digest = instance.digest(newPwd.getBytes("UTF-8"));
			//产生加密密码
			encodeHexString = Hex.encodeHexString(digest);
			model.setPassword(encodeHexString);
			this.getDao().updateSelective(model);
			result.setStatus(ReturnStatusEnum.SUCCESS.getCode());
			result.setMsg(ReturnStatusEnum.SUCCESS.getDesc());
			result.setReturnCode(OpReturnCodeEnum.OP_UPDATE_SUCCESS.getCode());
			result.setReturnMsg(OpReturnCodeEnum.OP_UPDATE_SUCCESS.getDesc());
			
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		return result;
	}
	/**
	 * 
	 * 功能:新增分店时为超级管理员添加分店权限 <br/>
	 * 
	 * 重写：zhousc <br/>
	 * 
	 * @Date ：2017年12月7日 下午3:00:13<br/>
	 * 
	 * @param hotelId
	 * @param groupId
	 * @return <br/>
	 * @see com.yuju.login.service.IOpService#saveHotelAfter(java.lang.String, java.lang.String)
	 */
	@Override
	public int saveHotelAfter(String hotelId, String groupId) {
		OpModel opModel = new OpModel();
		opModel.setGroupId(groupId);
		opModel.setIsAdmin(StatusEnum.TRUE.getValue());
		List<OpModel> list = this.getDao().list(getBeanMap(opModel));
		//为管理员账号添加分店权限
		OpHotelModel opHotelModel = new OpHotelModel();
		opHotelModel.setHotelId(hotelId);
		opHotelModel.setGroupId(groupId);
		opHotelModel.setOpId(list.get(0).getId());
		
		return opHotelService.save(opHotelModel);
	}

	/**
	 * 
	 * 功能:重名校验 <br/>
	 * 
	 * 重写：zhousc <br/>
	 * 
	 * @Date ：2017年12月13日 下午4:17:39<br/>
	 * 
	 * @param opModel
	 * @return <br/>
	 * @see com.yuju.login.service.IOpService#selectByName(com.yuju.login.model.OpModel)
	 */
	@Override
	public boolean selectByName(OpModel opModel) {
		// TODO Auto-generated method stub
		//定义返回值
		boolean result = false;
		//装载数据查询数据库
		OpModel model = new OpModel();
		model.setName(opModel.getName());
		model.setGroupId(opModel.getGroupId());
		
		//修改时验证重名
		if (Utils.isNotNull(opModel.getId())) {
			OpModel opModel1 = convert(this.getDao().getObj(opModel.getId()));
			if (opModel.getName().equals(opModel1.getName())) {
		            result = true;
		        } else {
		       	 	Map<Object, Object> beanMap = getBeanMap(model);
		            List<OpModel> list = this.getDao().list(beanMap);
		            if (list.size() == 0) {
		                result = true;
		            }
		        }
		//新增验证重名
		}else {
			Map<Object, Object> beanMap = getBeanMap(model);
		        List<OpModel> list = this.getDao().list(beanMap);
		        if (list.size() == 0) {
		            result = true;
		        }
		    }
		return result;
	}

	/**
	 * 
	 * 功能:微信注册 <br/>
	 * 
	 * 重写：zhousc <br/>
	 * 
	 * @Date ：2018年1月5日 下午6:16:02<br/>
	 * 
	 * @param opModel
	 * @return <br/>
	 * @see com.yuju.login.service.IOpService#saveWxGuest(com.yuju.login.model.OpModel)
	 */
	@Override
	public int saveWxGuest(OpModel opModel) {
		opModel.setUserType(UserTypeEnum.WECHAT_USER.getValue());
		opModel.setGmtCreate(new Date());
		opModel.setGmtModified(new Date());
		opModel.setSalt(Utils.getUUID());
		
		//对密码加密
		String password = opModel.getPassword();
		String salt = opModel.getSalt();
		//组合新密码
		String newPwd = opModel.getUserId() + password + salt;
		//进行SHA加密
		try {
			MessageDigest instance = MessageDigest.getInstance("SHA-256");
			byte[] digest = instance.digest(newPwd.getBytes("UTF-8"));
			//产生加密密码
			String encodeHexString = Hex.encodeHexString(digest);
			//装载数据
			opModel.setPassword(encodeHexString);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//账号添加
		return this.getDao().saveSelective(opModel);
		
	}
	
	/**
	 * 
	 * 功能:微信注册 <br/>
	 * 
	 * 重写：zhousc <br/>
	 * 
	 * @Date ：2018年1月5日 下午6:16:02<br/>
	 * 
	 * @param opModel
	 * @return <br/>
	 * @see com.yuju.login.service.IOpService#saveWxGuest(com.yuju.login.model.OpModel)
	 */
	@Override
	public int updateWxGuest(OpModel opModel) {
		OpModel m = new OpModel();
		m.setName(opModel.getMobile());
		List<OpModel> list = this.getDao().list(getBeanMap(m));
		
		if (Utils.isNull(list) || list.isEmpty()) {
			throw new BusinessException(ReturnCodeEnum.NO_REGISTER.getCode(), ReturnCodeEnum.NO_REGISTER.getDesc());
		}
		
		opModel.setId(list.get(0).getId());
		opModel.setName(opModel.getMobile());
		opModel.setGmtModified(new Date());
		
		//对密码加密
		String password = opModel.getPassword();
		String salt = list.get(0).getSalt();
		//组合新密码
		String newPwd = list.get(0).getUserId() + password + salt;
		//进行SHA加密
		try {
			MessageDigest instance = MessageDigest.getInstance("SHA-256");
			byte[] digest = instance.digest(newPwd.getBytes("UTF-8"));
			//产生加密密码
			String encodeHexString = Hex.encodeHexString(digest);
			//装载数据
			opModel.setPassword(encodeHexString);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//账号更新
		return this.getDao().updateSelective(opModel);
	}

	@Override
	public OpModel login(OpModel model) {
		return opDao.login(model);
	}
}
